package com.tstudy.laoshibang.share;

import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.StatusesAPI;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.sina.weibo.sdk.openapi.models.ErrorInfo;
import com.sina.weibo.sdk.openapi.models.User;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.base.HttpManager.LoadImageViewResponse;
import com.tstudy.laoshibang.login.ThirdLoginCallBack;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;
/**
 * Copyright: @com.ispied
 * 
 * @author: iSpiedImac
 * @date: May 31, 2013
 * @version: 1.0.0
 */
public class WrapSinaWeibo{
	private static WrapSinaWeibo mWarpWeibo;
	private AuthInfo mAuthInfo;
	private SsoHandler mSsoHandler;
	public Oauth2AccessToken mOauth2AccessToken;
	private String mShareImageUrl;
	ThirdLoginCallBack mLoginCallBack;
	
	boolean mIsBind;
	public enum WEIBO_ACTION{
		bind,share,get_friends,get_userInfo,login,bind_account
	}
	
	private WrapSinaWeibo(){
		mAuthInfo = new AuthInfo(BaseApplication.mContext, CONSTANT.WEIBO_APP_KEY,CONSTANT.REDIRECT_URL, "");
	}
	public static WrapSinaWeibo getInstance(){
		if(mWarpWeibo == null){
			mWarpWeibo = new WrapSinaWeibo();
		}
		return mWarpWeibo;
	}
	
	public void SSO(WEIBO_ACTION action,RequestListener listener){
		mSsoHandler = new SsoHandler(BaseApplication.mCurrentActivity, mAuthInfo);
		mSsoHandler.authorize(new AuthDialogListener());
	}
	
	BindCallBack mBindCallBack;
	BindAccountCallBack mBindAccountCallBack;
	public void setBindCallBack(BindCallBack bindCallBack){
		mBindCallBack = bindCallBack;
	}
	public interface BindCallBack {
		public void bindAction(boolean result);
	}
	public interface BindAccountCallBack {
		public void bindAccountAction(long sinaId);
	}
	
	//分享绑定
	public void bindSina(){
		mIsBind = true;
		mOauth2AccessToken = AccessTokenKeeper.readAccessToken(BaseApplication.mCurrentActivity);
		if (mOauth2AccessToken == null || !mOauth2AccessToken.isSessionValid()) {
			SSO(WEIBO_ACTION.bind,null);
		}else{
			mBindCallBack.bindAction(true);
		}
	}
	
	public boolean isBind(){
		mOauth2AccessToken = AccessTokenKeeper.readAccessToken(BaseApplication.mCurrentActivity);
		
		return mOauth2AccessToken == null ?false:mOauth2AccessToken.isSessionValid();
	}
	
	public void unBind(){
		mIsBind = false;
		AccessTokenKeeper.clear(BaseApplication.mCurrentActivity);
	}

	/**
	 * 分享微博
	 * @param shareStr
	 * @param imageUrl
	 */
	public void shareToWeibo(String content,String shareUrl,String imageUrl) {
		content = CommonUtil.subStr(content, 140-CommonUtil.getStrLength(shareUrl));
		content += shareUrl;
		mShareImageUrl = imageUrl;
		mOauth2AccessToken = AccessTokenKeeper.readAccessToken(BaseApplication.mCurrentActivity);
		if (mOauth2AccessToken.isSessionValid()) {
//			if (TextUtils.isEmpty(mShareImageUrl)) {
//				sendTxtToWeibo(content);
//			}else{
//				uploadUrlText(content,imageUrl);
			upload(content, imageUrl);
//			}
			
		} else {
			SSO(WEIBO_ACTION.share,null);
		}
	}
	
	/**
	 * 发送文本微博
	 */
	public void sendTxtToWeibo(String content) {
		StatusesAPI api = new StatusesAPI(BaseApplication.mContext, CONSTANT.WEIBO_APP_KEY, mOauth2AccessToken);
		api.update(content,BaseApplication.mCurrentAddress.latitude+"",BaseApplication.mCurrentAddress.longitude+"",new RequestListener() {
			
			@Override
			public void onWeiboException(WeiboException arg0) {
				destroyWrapWeibo();
			}
			
			@Override
			public void onComplete(String arg0) {
				BaseApplication.showToast(R.string.share_success);
				destroyWrapWeibo();
			}
		});
		
	}

	/**
	 * 发送图文微博
	 */
	public void uploadUrlText(String content,String url) {
		StatusesAPI api = new StatusesAPI(BaseApplication.mContext, CONSTANT.WEIBO_APP_KEY, mOauth2AccessToken);
		api.uploadUrlText(content, url, "",BaseApplication.mCurrentAddress.latitude+"",BaseApplication.mCurrentAddress.longitude+"",new RequestListener() {
			
			@Override
			public void onWeiboException(WeiboException arg0) {
				BaseApplication.showToast(R.string.share_failed);
				destroyWrapWeibo();
			}
			
			@Override
			public void onComplete(String arg0) {
				BaseApplication.showToast(R.string.share_success);
				destroyWrapWeibo();
			}
		});
	}
	
	/**
	 * 发送图片微博
	 */
	public void upload(final String content,String url) {
		final RequestListener lisenter = new RequestListener() {
			@Override
			public void onWeiboException(WeiboException arg0) {
				BaseApplication.showToast(R.string.share_failed);
				destroyWrapWeibo();
			}
			
			@Override
			public void onComplete(String arg0) {
				BaseApplication.showToast(R.string.share_success);
				destroyWrapWeibo();
			}
		};
		final StatusesAPI api = new StatusesAPI(BaseApplication.mContext, CONSTANT.WEIBO_APP_KEY, mOauth2AccessToken);
		if (TextUtils.isEmpty(url)) {
			Bitmap bitmap = BitmapFactory.decodeResource(BaseApplication.mContext.getResources(), R.drawable.welcome);
			api.upload(content, bitmap,BaseApplication.mCurrentAddress.latitude+"",BaseApplication.mCurrentAddress.longitude+"",lisenter);
			
		}else{
			HttpManager.getInstance().downLoadImage(url, new LoadImageViewResponse() {
				@Override
				public void loadFinish(Bitmap bitmap) {
					api.upload(content, bitmap,BaseApplication.mCurrentAddress.latitude+"",BaseApplication.mCurrentAddress.longitude+"",lisenter);
					
				}
			});
		}
		
	}
	
	  /**
     * 微博认证授权回调类。
     * 1. SSO 授权时，需要在 {@link #onActivityResult} 中调用 {@link SsoHandler#authorizeCallBack} 后，
     *    该回调才会被执行。
     * 2. 非 SSO 授权时，当授权结束后，该回调就会被执行。
     * 当授权成功后，请保存该 access_token、expires_in、uid 等信息到 SharedPreferences 中。
     */
    class AuthDialogListener implements WeiboAuthListener {
        
        @Override
        public void onComplete(Bundle values) {
            // 从 Bundle 中解析 Token
//        	BaseApplication.showToast("onComplete");
        	mOauth2AccessToken = Oauth2AccessToken.parseAccessToken(values);
            if (mOauth2AccessToken.isSessionValid()) {
                // 显示 Token
//                updateTokenView(false);
                // 保存 Token 到 SharedPreferences
                AccessTokenKeeper.writeAccessToken(BaseApplication.mContext, mOauth2AccessToken);
//                Toast.makeText(BaseApplication.mContext, 
//                        R.string.weibosdk_demo_toast_auth_success, Toast.LENGTH_SHORT).show();
                getUserInfo(Long.parseLong(mOauth2AccessToken.getUid()));
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
                LogUtil.d("weibo sso code ==" + code);
//                BaseApplication.showToast("sso code==" + code);
                String message = BaseApplication.getResString(R.string.weibosdk_demo_toast_auth_failed);
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
//                Toast.makeText(BaseApplication.mContext, message, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancel() {
            Toast.makeText(BaseApplication.mContext, 
                    R.string.weibosdk_demo_toast_auth_canceled, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
//            Toast.makeText(BaseApplication.mContext, 
//                    "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG).show();
        	
//        	 BaseApplication.showToast("sso code==");
        }
    }
	
	
	public void destroyWrapWeibo() {
		mWarpWeibo = null;
	}

	/**
	 * activityResult
	 * 
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 */
	public void activityResult(int requestCode, int resultCode, Intent data) {
		if (mWarpWeibo != null && mWarpWeibo.mSsoHandler != null) {
			mWarpWeibo.mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	
	public void weiboLogin(ThirdLoginCallBack callback) {
		mLoginCallBack = callback;
		mOauth2AccessToken = AccessTokenKeeper.readAccessToken(BaseApplication.mContext);
		if (mOauth2AccessToken.isSessionValid() && !TextUtils.isEmpty(mOauth2AccessToken.getUid())) {
			getUserInfo(Long.parseLong(mOauth2AccessToken.getUid()));
		} else {
			SSO(WEIBO_ACTION.get_userInfo,null);
		}
	}
	
	/**
     * 微博 OpenAPI 回调接口。
     */
    private RequestListener mListener = new RequestListener() {
        @Override
        public void onComplete(String response) {
            if (!TextUtils.isEmpty(response)) {
                // 调用 User#parse 将JSON串解析成User对象
                User user = User.parse(response);
                if (user != null) {
//                    Toast.makeText(BaseApplication.mContext, 
//                            "获取User信息成功，用户昵称：" + user.screen_name, 
//                            Toast.LENGTH_LONG).show();
                    if (mLoginCallBack != null) {
						mLoginCallBack.onSuccess(CONSTANT.USER_SOURCE_WEIBO,user.id, user.screen_name, "m".equals(user.gender)?1:0, user.avatar_large);
					}
                } else {
                    Toast.makeText(BaseApplication.mContext, response, Toast.LENGTH_LONG).show();
                }
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
        	if (mLoginCallBack != null) {
				mLoginCallBack.onFailed(e.toString());
			}
            ErrorInfo info = ErrorInfo.parse(e.getMessage());
//            Toast.makeText(BaseApplication.mContext, info.toString(), Toast.LENGTH_LONG).show();
        }
    };
	
	/**
	 * 获取用户详细信息
	 * @param values
	 */
	private void getUserInfo(long uid) {
		mOauth2AccessToken = AccessTokenKeeper.readAccessToken(BaseApplication.mContext);
        // 获取用户信息接口
		UsersAPI mUsersAPI = new UsersAPI(BaseApplication.mContext, CONSTANT.WEIBO_APP_KEY, mOauth2AccessToken);
		mUsersAPI.show(uid,mListener);
			
	}
	
	public interface WeiboLoginCallInterface {
		public void loginSuccess();
	}
	

}
